window.setInterval("updateChat()", 1000);

/*function onReceivePing(request) {
 if(request.responseText.indexOf('c') != -1)
   updateChat();
}*/

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function onReceiveChat(request) {
 var resptext = trim(request.responseText);
 var idx = resptext.indexOf("\n");
 var last = resptext.substring(0,idx);
 document.getElementById("statustext").innerHTML = "lastmsg: "+document.getElementById("lastmsg").value + ", newmsgs: "+last;
 if (document.getElementById("lastmsg").value*1 < last*1) {
   document.getElementById("statustext").innerHTML += ", new > last";
   var objDiv = document.getElementById("messarea");
   var wasdown = false;
   if(objDiv.scrollTop > (objDiv.scrollHeight-objDiv.offsetHeight)) wasdown = true;
   var c = document.getElementById("chat");
   c.innerHTML += resptext.substring(idx);
   document.getElementById("lastmsg").value = last;
   if(wasdown) objDiv.scrollTop = objDiv.scrollHeight;
 }
}

/*function pingServer(ms) {
 ajaxGet("ping", onReceivePing);
}*/

function updateChat(ms) {
	var lm = document.getElementById("lastmsg");
    ajaxGet("getchat?lastmsg="+escape(lm.value), onReceiveChat);
}

function submitenter(myfield,e,name) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13) {
        sendMessage(name);
        return false;
    } else return true;
}

function sendMessage(name) {
    var m = document.getElementById("message");
    ajaxGet("putchat?person=" + escape(name) + "&message=" + escape(m.value), onReceiveChat);
    m.value = "";
    m.focus();
}

function addText(t) {
	var m = document.getElementById("message");
	m.value += t;
}
